const mysql = require('./mysql');

let insertTopic_comment = async function (topicId, userId, content) {
    if(userId == null){
        return
    }
    content = content.replace(/'/g,`''`);
    let sql = `insert into topic_commect(topic_id,user_id,content) values(${topicId},${userId},'${content}');`;
    return await mysql.asyncExec(sql);
}

let getAllEntires = async function () {
    let sql = `select * from topic_commect`;
    return await mysql.asyncExec(sql);
}

let getAllEntiresBytopicId = async function (topicId) {
    let sql = `select * from topic_commect where topic_id = ${topicId}`;
    return await mysql.asyncExec(sql);
}

let getBetweenEntries = async function (first, last, topicId) {
    let sql = `select * from topic_commect where topic_id = ${topicId} order by id desc limit ${first},${last} `;
    return await mysql.asyncExec(sql);
}

let getEntriesCount = async function (topicId) {
    let sql = `select count(*) from topic_commect where topic_id = ${topicId}`;
    let result = await mysql.asyncExec(sql);
    //直接返回数字结果
    return result[0]['count(*)'];
}

const MAXpathEntries = 9;

let getSplitTopicComment = async function(queryPath,topicId) {
    //topic条目总数
    let topicNum = await getEntriesCount(topicId);
    //path整数
    let pathIntNum = parseInt(topicNum / MAXpathEntries);
    //path余数
    let pathMod = pathIntNum % MAXpathEntries;
    //path总数，如果有余数就+1
    let pathNum = pathIntNum + (pathMod != 0 ? 1 : 0);

    //query的值，大于总页数就让他
    if (queryPath > pathNum) {
        queryPath = pathNum;
    }

    if(queryPath < 1){
        queryPath = 1;
    }

    //当前的页码
    let currentPathNum = queryPath;
    //剩余的path数
    let exitsToicNum = pathNum - currentPathNum + 1;

    //到数据库获取值
    let last = currentPathNum * MAXpathEntries;
    let first = last - MAXpathEntries;
    let topicComment = await getBetweenEntries(first, MAXpathEntries,topicId);

    return {
        pathNum,        //path总数，如果有余数就+1
        exitsToicNum,   //剩余的path数
        currentPathNum, //当前的页码
        topicComment        //内容主体
    }
}

module.exports ={
    insertTopic_comment,
    getAllEntires,
    getAllEntiresBytopicId,
    getEntriesCount,
    getBetweenEntries,
    getSplitTopicComment
}